package newtank.view.operate;

import newtank.data.ShootSignal;
import newtank.utils.ExecutorsUtils;
import newtank.view.BulletView;
import newtank.view.PaintView;
import newtank.view.TankView;
import newtank.view.context.BulletViewContext;
import newtank.view.context.TankViewContext;

import java.awt.event.KeyEvent;

/**
 * @author lijiahao
 * @since 2022/3/8
 */
public class ShootHandler extends AbstractOperatorHandler{

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if(KeyEvent.VK_SPACE == code) {
            shoot();
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void run() {

    }

    private void shoot() {
        TankViewContext tankViewContext = tankClientFrame.getSelfTankContext();
        String tankId = tankViewContext.getTankId();
        BulletViewContext bulletViewContext = new BulletViewContext();
        PaintView paintView = tankDrawingCloth.getView(tankId);
        if(paintView instanceof TankView) {
            TankView tankView = (TankView) paintView;
            tankView.shooting(bulletViewContext);
        }
        tankDrawingCloth.addPaintView(new BulletView(bulletViewContext));
        ExecutorsUtils.execute(bulletViewContext);
        if(tankClientFrame != null) {
            tankClientFrame.sendMessage(new ShootSignal(tankId));
        }
    }
}
